<template>
  <div class="c-popup z-index-popup" :class="{'hide' : !show}" mask>
    <div class="popup-body">
      <i class="popup-close" @click="doClose"></i>
      <div class="popup-header">
        <span>下载管理</span>
      </div>
      <div class="popup-content content-box">
        <!--    列表内容    -->
        <div class="content-table-box">
          <!--     下载完成列表     -->
          <div class="table-box">
            <el-table
              ref="videoDownLoadTable"
              class="video-download-table"
              :data="downloadingData.downloadingList"
              style="width: 100%"
            >
              <el-table-column type="index" label="序号"  width="52" :show-overflow-tooltip="false"
              ></el-table-column>
              <el-table-column label="通道名称"  min-width="220" width="" :show-overflow-tooltip="false">
                <template slot-scope="scope">
                  <div class="table-div-left" :c-tip="scope.row.channelName" c-tip-placement="top" c-tip-auto>
                    {{ scope.row.channelName }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="录像时间"  width="334" :show-overflow-tooltip="false">
                <template slot-scope="scope">
                  <div class="table-div" :c-tip="scope.row.newVideoDate" c-tip-placement="top" c-tip-auto>
                    {{ scope.row.newVideoDate }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="文件大小"  width="80" :show-overflow-tooltip="false">
                <template slot-scope="scope">
                  <div class="table-div" :c-tip="scope.row.fileSize" c-tip-placement="top" c-tip-auto>
                    {{ scope.row.fileSize }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="状态"  width="80" :show-overflow-tooltip="false">
                <template slot-scope="scope">
                  <div class="table-div" :c-tip="scope.row.status" c-tip-placement="top" c-tip-auto>
                    {{ scope.row.status }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="进度"  width="80" :show-overflow-tooltip="false">
                <template slot-scope="scope">
                  <div class="table-div" :c-tip="scope.row.process" c-tip-placement="top" c-tip-auto>
                    {{ scope.row.process }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="操作"  width="62" :show-overflow-tooltip="false">
                <template slot-scope="scope">
                  <div class="y-table-btn">
                    <el-button
                      c-tip="删除"
                      c-tip-placement="top"
                      type="text"
                      class="table-btn"
                      icon="iconfont icon-tongyong_icon_biaogeshanchu1 table-btn-icon"
                      @click="handleDelete(scope.row)"
                    ></el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>
            <!-- 下载完成表格分页-->
            <div class="pagination-box" v-show="downloadingData.total > 0">
              <div class="page-number">
                第{{ downloadingData.pageNum }}页/共{{ downloadingData.total }}条
              </div>
              <el-pagination
                @current-change="downloadHandleCurrentChange"
                :current-page="downloadingData.pageNum"
                :page-size="downloadingData.pageSize"
                layout="prev, pager, next"
                small
                :total="downloadingData.total"
                :pager-count="5"
              />
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>

import { deleteRecordDownload, downloadProcess, recordDownloadList, stopDownloadVideo } from '@/api/video';
import { saveAs } from 'file-saver';
import axios from 'axios';

export default {
  name: 'video-download-manage',
  props: {
    //下载管理的显示与隐藏
    show: {
      type: Boolean,
      default: false
    },
    //下载管理列表数据
    // [{
    //   deviceCode: '10000000001',
    //   channelCode: '1000000001001',
    //   channelName: '铁塔产业园-11号楼',
    //   videoDate: ['2016-05-02 10:00:00','2016-05-02 16:00:00'],
    //   }]
    videoDownloadManageList: {
      type: Array,
      default: []
    }
  },
  watch: {
    // 'show': {
    //   handler() {
    //     if (this.show) {
    //       this.getDownList();
    //       clearInterval(this.timer);
    //       this.timer = setInterval(() => {
    //         this.refreshDownLoadList();
    //       }, 2000);
    //     }
    //   },
    //   deep: true,//json 深度匹配
    //   immediate: true//初始化时执行
    // }
  },
  data() {
    return {
      //下载完成数据
      downloadManageList: [],
      //前端分页后下载完成数据
      downloadingData: {
        downloadingList: [],
        pageNum: 1,
        pageSize: 5
      },
      //下载完成列表
      downloadOverList: [],
      downloadOverParam: {
        list: [],
        pageNum: 1,
        pageSize: 5,
        total: 0
      },
      //是否是下载完成页面 tab切换
      isOver: false
    };
  },
  mounted() {
    this.getDownList();
    clearInterval(this.timer);
    this.timer = setInterval(() => {
      this.refreshDownLoadList();
    }, 2000);
  },
  beforeDestroy() {
    clearInterval(this.timer);
    this.stopDownloadVideo(this.videoDownloadManageList);
  },
  methods: {
    /**
     * 关闭属性
     */
    doClose() {
      this.$emit('videoDownloadManageClose');
    },
    /**
     * 处理下载数据
     */
    handleListData(list) {
      let arr = JSON.parse(JSON.stringify(list));//深度克隆
      let newList = [];
      for (let item of arr) {//赋值页面展示数据
        item.newVideoDate = item.startTime + '~' + item.endTime;
        newList.push(item);
        if(item.downloadStatus === 1) {//已完成
          item.status = '下载完成';
          item.process = '';
          if(!String(item.fileSize).includes('MB')){
            item.fileSize += 'MB';
          }
        }else if(item.downloadStatus === 0){//未完成
          item.status = '准备中';
          if(item.process == null){
            item.process = '';
          }
        }else{//下载失败
          item.status = '下载失败';
          item.process = '';
        }
      }
      this.downloadingData.downloadingList = newList;
    },
    /**
     * 格式化时间串
     * @param dateString
     * @returns {string}
     */
    formatDate(dateString) {
      const date = new Date(dateString);
      const year = date.getFullYear();
      const month = ("0" + (date.getMonth() + 1)).slice(-2);
      const day = ("0" + date.getDate()).slice(-2);
      const hour = ("0" + date.getHours()).slice(-2);
      const minute = ("0" + date.getMinutes()).slice(-2);
      const second = ("0" + date.getSeconds()).slice(-2);
      return `${year}${month}${day}${hour}${minute}${second}`;
    },
    /**
     * 更新列表数据
     */
    updateListData() {
      this.handleListData(this.downloadingData.downloadingList);
    },
    /**
     * 判断百分比字符串是否大于0
     * @returns {boolean}
     * @param percentageString
     */
    isPercentageGreaterThanZero(percentageString) {
      // 使用正则表达式来提取数字部分
      const numberMatch = percentageString.match(/\d+(\.\d+)?/);

      // 检查是否有匹配的数字
      if (numberMatch) {
        // 解析数字部分并转换为浮点数
        const number = parseFloat(numberMatch[0]);

        // 判断数字是否大于0
        return number > 0;
      }

      // 如果没有匹配的数字，返回false
      return false;
    },
    /**
     * 生成uuid
     */
    getUUID() {
      const crypto = window.crypto || window.msCrypto;
      const array = new Uint32Array(1);
      const r = crypto.getRandomValues(array)[0];
      return Date.now() + '2' + r;
    },
    /**
     * 删除行事件(下载完成)
     * @param row
     */
    handleDelete(row) {
      const _this = this;
      this.stopDownloadVideo([row]);
      deleteRecordDownload({id: row.id}).then(()=>{
        this.downloadManageList = _this.downloadingData.downloadingList.filter(item => item.id !== row.id);
        //总页数（每次删除计算总页数）
        if(_this.downloadManageList.length < 1){
          //当前页已经删除最后一条数据, 跳转到上一页
          _this.downloadingData.pageNum = _this.downloadingData.pageNum - 1;
        }

        //当页数小于为0 就给它为1页 否则就还是当前页
        if(_this.downloadingData.pageNum < 1){
          _this.downloadingData.pageNum = 1;
        }
        this.getDownList(_this.downloadingData.pageNum);
      });
    },
    /**
     * 下载到本地
     * @param url
     * @param fileName
     */
    downLoadToLocal(url, fileName) {
      axios({
        url: url,
        method: 'GET',
        responseType: 'blob',
        onDownloadProgress: (progressEvent) => {
          this.progress = Math.round((progressEvent.loaded * 100) / progressEvent.total);
        }
      }).then((response) => {
        saveAs(response.data, fileName);
      }).catch((error) => {
        console.error('Download failed', error);
      });
    },
    /**
     * 切换列表分页（下载完成）
     * @param num 页码
     */
    downloadHandleCurrentChange(num) {
      this.downloadingData.pageNum = num;
      this.getDownList(num);

    },
    /**
     * 实时获取下载列表
     */
    getDownList(pageNum){
      let size = this.downloadingData.pageSize;
      recordDownloadList({
        pageNum: pageNum ? pageNum : 1,
        pageSize: size
      }).then(({ data }) => {
        this.downloadingData.total = data.total;
        this.handleListData(data?.rows);
      });
    },
    /**
     * 刷新下载列表
     */
    refreshDownLoadList() {
      const _this = this;
      this.queryDownloadProcess((data) => {
        let changeNum = 0;
        for (const item of _this.downloadingData.downloadingList) {
          const dataElement = data[item.batchId];
          const statusList = ['下载完成', '下载失败'];
          if (dataElement == null || statusList.includes(item.status)) {
            //接口没有返回, 已经标记状态的不处理
            continue;
          }
          if (String(dataElement?.processCode) === '1000' || String(dataElement?.processCode) === '0') {
            //没有计算出最大值并且当前下载大小大于0并且百分比不是0%
            if (item.fileMaxSize == null && dataElement.fileSize != null && dataElement.fileSize > 0
              && this.isPercentageGreaterThanZero(dataElement.process)) {
              // 从百分比字符串中提取数字部分
              const percentageNumber = parseFloat(dataElement.process.slice(0, -1));
              // 计算100%的值
              item.fileMaxSize = ((dataElement.fileSize / percentageNumber) * 100).toFixed(2);
            }
            if (item.fileMaxSize != null) {//已经计算出最大值了
              item.fileSize = `${item.fileMaxSize}MB`;//`${dataElement.fileSize}MB/${item.fileMaxSize}MB`
              item.process = dataElement.process;
            }
            if (dataElement.process === '100%') {//下载完成了
              changeNum++;
              item.status = '下载完成';
              item.process = '';
              item.downloadUrl = dataElement.downloadUrl;
              item.fileName = dataElement.fileName;
              setTimeout(() => {
                //拼接下载文件名称: 摄像机名称_设置下载任务开始时间_设置下载任务结束时间
                const startStr = this.formatDate(item.startTime);
                const endStr = this.formatDate(item.endTime);
                const fileName = `${item.deviceName}_${startStr}_${endStr}.mp4`
                this.downLoadToLocal(dataElement.downloadUrl, fileName);
              });
            }
          } else {//下载失败
            changeNum++;
            item.status = '下载失败';
            item.process = '';
            item.fileSize = '';
          }
        }
        if(changeNum > 0){//有数据失败或下载完成重新调用接口查询列表,防止数据多有未下载的在后面
          this.getDownList();
        }else{
          this.updateListData();
        }
      });
    },
    /**
     * 查询下载录像百分比
     * @param successFn 成功回调
     * @returns {boolean}
     */
    queryDownloadProcess(successFn) {
      //正在下载的数据
      let queryList = this.getDownLoadingList(this.downloadingData.downloadingList);
      //回调事件downloading, 返回正在下载的数量
      this.$emit('downloading', queryList.length);
      if (queryList.length === 0) {
        //无需要查询的数据不调用接口
        return false;
      }
      downloadProcess(queryList).then((resp) => {
        successFn(resp.data);
      });
    },
    /**
     * 批量停止下载
     * @param list
     * @returns {boolean}
     */
    stopDownloadVideo(list) {
      let queryList = this.getDownLoadingList(list);
      if (queryList.length === 0) {
        //无需要停止的数据不调用接口
        return false;
      }
      stopDownloadVideo(queryList).then();
    },
    /**
     * 获取正在下载的数据
     * @param allList 全部状态数据
     * @returns {*[]}
     */
    getDownLoadingList(allList){
      let list = [];
      for (const item of allList) {
        if (item.status !== '下载失败' && item.status !== '下载完成') {
          list.push({
            startTime: item.startTime,
            endTime: item.endTime,
            deviceCode: item.deviceCode,
            channelCode: item.channelCode,
            storageType: item.storageType,
            batchId: item.batchId
          });
        }
      }
      return list;
    }
  }
};
</script>
<style lang="scss" scoped>
.c-popup.z-index-popup{
  z-index: 20009!important;
}
.c-popup.hide {
  display: none !important;
}

.popup-body {
  height: 424px;
  width: 932px;
}

/*头部标题*/
/*内容盒子*/
.content-box {
  padding: 12px 12px;
  /*内容头部tab盒子*/

  /*表格内容*/
  .content-table-box {
    width: 100%;
    height: auto;

    .table-box {
      width: 100%;
      margin-bottom: 12px;
      /* 表格 */
      /deep/ .el-table {
        background: transparent;
        font-size: 14px;
        &:before {
          background: transparent;
        }
        /*表格头部*/
        .el-table__header-wrapper {
          .el-table__header {
            .has-gutter {
              .is-leaf {
                background: rgba(79, 159, 255, 0.2);
                color: #E8F1FD;
                border-bottom: 1px solid rgba(232,243,254,0.2);
                padding: 0;

                .cell {
                  height: 32px;
                  line-height: 32px;
                  font-size: 14px;
                  color: #E8F3FE;
                }
              }
            }
          }
        }

        /*表格内容*/
        .el-table__body-wrapper {
          /*无数据*/
          .el-table__empty-block {
            height: 240px !important;
            position: relative;
            .el-table__empty-text {
              display: flex !important;
              align-items: center;
              justify-content: center;
              flex-direction: column;
              color: #E8F3FE !important;
              height: 100% !important;
              width: 100% !important;
              padding-top: 46px;
              position: static !important;
              line-height: 1;
              &:before {
                content: "";
                display: block;
                width: 68px;
                height: 68px;
                background: url("~@/assets/image/noData.png") no-repeat center / 100% 100% !important;
                margin: 0 0 12px 0 !important;
                position: static !important;
              }
            }
          }

          /*有数据*/
          .el-table__body {
            .el-table__row {
              height: 32px;
              line-height: 32px;

              td {
                border-bottom: 1px solid rgba(232,243,254,0.2);
              }
              .el-table__cell{
                padding: 12px 0px;
              }
            }

            .current-row {
              td {
                background: transparent;

                div {
                  font-size: 14px;
                  font-weight: normal;
                  color: #E8F3FE !important;
                }
              }
            }
          }
        }
      }

      /deep/ .el-table--enable-row-hover .el-table__body tr:hover > td {
        background: transparent;
      }

      /deep/ .el-table th.el-table__cell.is-leaf {
        background: transparent;
        color: #E8F3FE !important;
      }

      /deep/ .el-table th.el-table__cell > .cell {
        color: #E8F3FE !important;
      }

      /deep/ .el-table tr {
        background: transparent !important;
      }

      /deep/ .el-table .cell {
        padding: 0 12px;
        color: #E8F3FE !important;
      }

      /* 列表 分页*/
      .pagination-box {
        width: 100%;
        height: 22px;
        line-height: 22px;
        position: absolute;
        bottom: 12px;
        right: 12px;
        display: flex;
        justify-content: flex-end;
        font-size: 12px;

        .page-number {
          height: 22px;
          font-weight: 400;
          color: #E8F3FE;
          line-height: 22px;
        }

        /deep/ .el-pagination {
          padding: 0 !important;
          .btn-prev, .btn-next {
            width: 20px;
            height: 22px;
            min-width: unset;
            line-height: 22px;
            margin-left: 6px;
            padding: 0;

            .el-icon {
              font-size: 12px;

              &:before {
                position: relative;
                top: 1.5px;
              }
            }
          }
          .el-pager .number {
            width: 22px;
            height: 22px;
            min-width: unset;
            padding: 0;
            box-sizing: border-box;
            line-height: 22px;
            font-size: 12px;
            border-radius: 4px;
            margin-left: 6px;
          }
        }
        /deep/ .el-pagination .el-pager li,
        /deep/ .el-pagination .btn-next,
        /deep/ .el-pagination .btn-prev {
          color: #fff !important;
          background: transparent !important;
        }
        /deep/ .el-pagination .btn-next:disabled,
        /deep/ .el-pagination .btn-prev:disabled {
          opacity: 0.4!important;
        }

        /deep/ .el-pagination .el-pager li.active {
          background: #4F9FFF !important;
          border-radius: 4px !important;
          color: #fff !important;
        }
      }
    }
  }

  /*列表按钮*/
  .y-table-btn {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    //justify-content: center;

    .table-btn {
      color: #E8F3FE;

      /deep/ .table-btn-icon {
        font-size: 24px;
      }
    }

    .disable-table-btn {
      opacity: 0.4;
    }
  }
}

.table-div {
  width: 100%;
  height: auto;
  text-align: left;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.table-div-left {
  width: 100%;
  height: auto;
  text-align: left;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.l2,.ar-l2 {
  .popup-body {
    height: 424px;
    width: 934px;
  }
  .content-box .content-table-box /deep/ .el-table .el-table__header-wrapper .el-table__header .has-gutter .is-leaf {
    background: rgba(2, 137, 109, 0.2) !important;
  }

  .content-box .content-table-box /deep/ .table-box .pagination-box .el-pagination .el-pager li.active {
    background: rgba(2, 137, 109, 1) !important;
  }

  .content-box .content-table-box /deep/ .table-box .el-table .el-table__body-wrapper .el-table__empty-block .el-table__empty-text {
    color: #fff !important;
    &:before {
      background-image: url("~@/assets/image/noData-ly.png") !important;
    }
  }

  .content-box .content-table-box .table-box /deep/ .el-table .cell,
  .content-box .content-table-box .table-box /deep/ .pagination-box .page-number,
  .content-box .content-table-box .table-box .pagination-box /deep/ .el-pagination .el-pager li,
  .content-box .content-table-box .table-box .pagination-box /deep/ .el-pagination .btn-next,
  .content-box .content-table-box .table-box .pagination-box /deep/ .el-pagination .btn-prev {
    color: #FFFFFF !important;
  }

  .content-box .content-table-box .table-box /deep/ .el-table th.el-table__cell > .cell {
    color: #FFFFFF !important;
  }
  /*列表按钮*/
  .y-table-btn {
    .table-btn {
      color: #FFFFFF;
    }
  }
  .c-popup /deep/ .popup-body .popup-content{
    background: none;
  }
}

.g,.ar-g {
  .popup-body {
    height: 424px;
    width: 934px;
  }
  .content-box .content-table-box /deep/ .el-table .el-table__header-wrapper .el-table__header .has-gutter .is-leaf {
    background: rgba(122, 113, 61, 0.36) !important;
  }

  .content-box .content-table-box /deep/ .table-box .pagination-box .el-pagination .el-pager li.active {
    background: rgba(159, 152, 83, 1) !important;
  }

  .content-box .content-table-box /deep/ .table-box .el-table .el-table__body-wrapper .el-table__empty-block .el-table__empty-text {
    color: #E4E7C1 !important;
    &:before {
      background-image: url("~@/assets/image/noData-gt.png") !important;
    }
  }

  .content-box .content-table-box .table-box /deep/ .el-table .cell,
  .content-box .content-table-box .table-box /deep/ .pagination-box .page-number,
  .content-box .content-table-box .table-box .pagination-box /deep/ .el-pagination .el-pager li,
  .content-box .content-table-box .table-box .pagination-box /deep/ .el-pagination .btn-next,
  .content-box .content-table-box .table-box .pagination-box /deep/ .el-pagination .btn-prev {
    color: #E4E7C1 !important;
    i{
      line-height: 23px;
    }
  }

  .content-box .content-table-box .table-box /deep/ .el-table th.el-table__cell > .cell {
    color: #FFEEB1 !important;
  }

  .c-popup /deep/ .popup-body .popup-content{
    background: none;
  }
  /*列表按钮*/
  .y-table-btn {
    .table-btn {
      color: #FFEEB1;
    }
  }
}
</style>
